// 创建链表节点

// 创建类：用于接收链表
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// 创造链表
function createNode() {
    const head = new Node(1);
    let node = head;
    for (let i = 2; i < 6; i++) {
        node.next = new Node(i);
        node = node.next;
    }
    return head;
}

class SingleLinkedList {

    constructor(nodeList) {
        this.nodeList = nodeList;
    }

    // 获取链表
    getNodeList() {
        let node = this.nodeList;
        let resultVal = '';
        while (node) {
            resultVal += `-> ${node.data} `;
            node = node.next;
        }
        console.log(resultVal);
        return this.nodeList;
    }

    // 寻找节点
    findNode(val) {
        let currentList = this.nodeList;
        while (currentList && currentList.data !== val) {
            currentList = currentList.next;
        }
        return currentList;
    }

    // 添加节点
    addNode(node) {
        if (!this.nodeList) {
            this.nodeList = node;
            this.getNodeList();
            return;
        }
        const next = this.nodeList.next;
        node.next = next;
        this.nodeList.next = node;
        this.getNodeList();
    }

    // 删除节点
    deleteNode(val) {
        let currentList = this.nodeList;
        let prev;
        if (currentList.data === val) {
            currentList = currentList.next && currentList.next;
            this.nodeList = currentList;
        }
        while (currentList && currentList.data !== val) {
            prev = currentList;
            currentList = currentList.next;
        }
        if (prev && prev.next) {
            prev.next = prev.next.next;
        }
        this.getNodeList();
    }
}

let nodeList = new SingleLinkedList(createNode());
nodeList.addNode(new Node(10));
nodeList.addNode(new Node(11));
nodeList.addNode(new Node(12));
nodeList.deleteNode(1);
nodeList.deleteNode(2);
nodeList.deleteNode(5);